<?php

namespace App\Http\Controllers\Home;

use App\Http\Requests\AddressRequest;
use App\models\Address;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AddressController extends CommonController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $addresses = Address::where('user_id',auth()->id())->orderBy('is_default','DESC')->get();
        return view('home.address_index',compact('addresses'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(AddressRequest $request)
    {
        $post = $request->all();
        $post['user_id'] = auth()->id();
        Address::create($post);
        return redirect()->route('home.address.index')->with('success','添加成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Address $address)
    {
//       dd($request->all());
       $data = $request->all();
//       因为默认地址只有一个，所以做了以下判断
       if ($data['is_default']==1)
       {
           Address::where('user_id',auth()->id())->update(['is_default'=>0]);
           $address->update($data);
       }elseif ($data['is_default']==0)
       {
           $address->update($data);
       }
        return redirect(route('home.address.index'))->with('success','修改成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Address $address)
    {
        $address->delete();
        return redirect(route('home.address.index'))->with('success','删除地址成功');
    }

    public function setDefault(Address $address)
    {
//        dd(123);
//         dd($address['id']);
//        先将所有该用户的收货地址默认地址字段改为非默认
        Address::where('user_id',auth()->id())->update(['is_default'=>0]);
//        将当前地址设置为默认地址
        $address->update(['is_default'=>1]);
        return back()->with('success','默认地址设置成功');
    }
}
